#include <iostream>
#include "stdafx.h"
#include "opencv2/opencv.hpp"

using namespace cv;
using namespace std;

bool descSort(vector<Point> p1, vector<Point> p2)
{
	return contourArea(p1) > contourArea(p2);
} 

int main()
{
   VideoCapture cap("D:\\cv_study\\GMM\\test.mp4");
   Mat frame, mask, result,srcImage;
   Ptr<BackgroundSubtractorMOG2>bgsubtractor = createBackgroundSubtractorMOG2();
   bgsubtractor->setVarThreshold(20);
   double fps = cap.get(cv::CAP_PROP_FPS);
   Size size = Size(cap.get(cv::CAP_PROP_FRAME_WIDTH), cap.get(cv::CAP_PROP_FRAME_HEIGHT));
   VideoWriter writer("D:\\cv_study\\GMM\\result.avi", CV_FOURCC('M', 'J', 'P', 'G'), fps, size);
	while (1)
	{
		cap >> frame;
		if (frame.empty())
			break;
		frame.copyTo(result);

		bgsubtractor->apply(frame, mask, 0.2);
		imshow("原视频", frame);
		medianBlur(mask, mask, 5);
		morphologyEx(mask, mask, MORPH_CLOSE, getStructuringElement(MORPH_RECT, Size(5, 5)));
		morphologyEx(mask, mask, MORPH_OPEN, getStructuringElement(MORPH_RECT, Size(5, 5)));
		imshow("混合高斯建模", mask);
		mask.copyTo(srcImage);
		vector<vector<Point>>contours;
		vector<Vec4i>h;
		findContours(srcImage, contours, RETR_EXTERNAL, CHAIN_APPROX_NONE,Point());
		Rect rect;
		sort(contours.begin(), contours.end(), descSort);
		for (int i = 0; i < contours.size(); i++)
		{
			if (contourArea(contours[i]) < contourArea(contours[0]) / 5)
				break;
			rect = boundingRect(contours[i]);
			rectangle(result, rect, Scalar(0, 0, 255), 1, 8);
			imshow("效果图", result);
			waitKey(30);
        }
		writer << result;


	}
    return 0;
}